<template>
	<view class="detail-container">
		<!-- 课程封面 -->
		<view class="course-header">
			<image class="course-banner" :src="courseDetail.image" mode="aspectFill"></image>
			<view class="course-info">
				<text class="course-title">{{ courseDetail.title }}</text>
				<view class="course-meta">
					<text class="students">{{ courseDetail.studentCount || 0 }}人学习</text>
				</view>
			</view>
		</view>
		
		<!-- 课程详情 Tab -->
		<view class="tab-box">
			<view 
				v-for="(tab, index) in tabs" 
				:key="index"
				:class="['tab-item', { active: currentTab === index }]"
				@tap="switchTab(index)"
			>
				{{ tab }}
			</view>
		</view>
		
		<!-- 课程内容 -->
		<swiper class="content-swiper" :current="currentTab" @change="swiperChange">
			<!-- 章节 -->
			<swiper-item>
				<scroll-view scroll-y="true" class="chapter-list">
					<view 
						v-for="(chapter, index) in courseDetail.chapters" 
						:key="index"
						class="chapter-item"
						@tap="goToChapter(chapter, index)"
					>
						<view class="chapter-title">
							<text class="chapter-index">{{ index + 1 }}</text>
							<text>{{ chapter.title }}</text>
						</view>
						<view class="chapter-right">
							<text class="chapter-duration">{{ chapter.duration }}</text>
							<text class="chapter-arrow">›</text>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
			
			
			<!-- 详情 -->
			<swiper-item>
				<scroll-view scroll-y="true" class="detail-content">
					<rich-text :nodes="courseDetail.description"></rich-text>
				</scroll-view>
			</swiper-item>
			
			<!-- 评价 -->
			<swiper-item>
				<scroll-view scroll-y="true" class="comment-list">
					<view 
						v-for="(comment, index) in courseDetail.comments" 
						:key="index"
						class="comment-item"
					>
						<image class="user-avatar" :src="comment.userAvatar"></image>
						<view class="comment-content">
							<view class="comment-header">
								<text class="user-name">{{ comment.userName }}</text>
								<text class="comment-time">{{ comment.createTime }}</text>
							</view>
							<text class="comment-text">{{ comment.content }}</text>
						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
		
		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="price-box">
				<text class="price">{{ courseDetail.price === 0 ? '免费' : `¥${courseDetail.price}` }}</text>
			</view>
			<button class="enroll-btn" @tap="enrollCourse">立即报名</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { courseApi } from '../../utils/api'

const tabs = ['章节', '详情', '评价']
const currentTab = ref(0)

// 课程详情数据
const courseDetail = ref({})

// 当前章节索引
const currentChapterIndex = ref(null)

// 当前章节内容
const currentChapterContent = ref('')

// 切换 Tab
const switchTab = (index) => {
	currentTab.value = index
}

// 滑动切换
const swiperChange = (e) => {
	currentTab.value = e.detail.current
}

// 报名课程
const enrollCourse = async () => {
	try {
		const res = await courseApi.enrollCourse({
			id: courseDetail.value.id
		})
		if (res.code === 0) {
			uni.showToast({
				title: '报名成功',
				icon: 'success'
			})
		}
	} catch (error) {
		console.error('报名失败:', error)
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
	}
}

// 获取章节内容
const getChapterContent = async (courseId, chapter) => {
	try {
		const res = await courseApi.getChapterContent(courseId, chapter)
		if (res.code === 0) {
			// 判断内容是否为空
			if (!res.data.content || res.data.content.trim() === '') {
				// 判断是否可以访问
				if (!res.data.canAccess) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						showCancel: false
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						success: (res) => {
							if (res.confirm) {
								// 跳转到登录页
								uni.navigateTo({
									url: '/pages/user/login'
								})
							}
						}
					})
				}
				return null
			}
			return res.data
		}
	} catch (error) {
		console.error('获取章节内容失败:', error)
		uni.showToast({
			title: '获取章节内容失败',
			icon: 'none'
		})
		return null
	}
}

// 切换章节
const switchChapter = async (direction) => {
	if (!courseDetail.value.chapters?.length) return
	
	let nextIndex
	if (direction === 'prev') {
		nextIndex = currentChapterIndex.value - 1
	} else {
		nextIndex = currentChapterIndex.value + 1
	}
	
	// 检查索引范围
	if (nextIndex < 0 || nextIndex >= courseDetail.value.chapters.length) return
	
	// 获取目标章节
	const targetChapter = courseDetail.value.chapters[nextIndex]
	
	try {
		// 获取新章节的内容
		const chapterData = await getChapterContent(courseDetail.value.id, nextIndex + 1)
		
		if (chapterData) {
			// 更新当前章节索引
			currentChapterIndex.value = nextIndex
			
			// 更新章节内容
			targetChapter.content = chapterData.content
			
			// 存储新的章节信息
			uni.setStorageSync('currentChapter', {
				...targetChapter,
				...chapterData,
				index: nextIndex + 1,
				courseTitle: courseDetail.value.title
			})
			
			// 更新 URL 参数但不重新加载页面
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			if (currentPage.$page) {
				currentPage.$page.options.chapter = nextIndex + 1
			}
			
			// 触发章节切换事件
			uni.$emit('chapterChange', {
				chapter: targetChapter,
				chapterData,
				index: nextIndex
			})
			
			// 显示切换成功示
			uni.showToast({
				title: '已切换到' + chapterData.title,
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('切换章节失败:', error)
		currentChapterIndex.value = nextIndex - (direction === 'next' ? 1 : -1)
	}
}

// 跳转到章节详情
const goToChapter = async (chapter, index) => {
	try {
		// 获取章节内容
		const chapterData = await getChapterContent(courseDetail.value.id, index + 1)
		
		if (chapterData) {
			// 更新当前章节索引
			currentChapterIndex.value = index
			
			// 存储当前章节信息
			uni.setStorageSync('currentChapter', {
				...chapter,
				...chapterData,
				index: index + 1,
				courseTitle: courseDetail.value.title
			})
			
			// 存储课程信息
			uni.setStorageSync('currentCourse', courseDetail.value)
			
			// 跳转到章节详情页
			uni.navigateTo({
				url: `/pages/course/chapter?id=${courseDetail.value.id}&chapter=${index + 1}`
			})
		}
	} catch (error) {
		console.error('获取章节内容失败:', error)
	}
}

// 获取课程详情
const getCourseDetail = async (id) => {
	try {
		let res
		// #ifdef MP-WEIXIN
		res = await uni.request({
			url: 'http://localhost:8080/api/course/get',
			method: 'GET',
			data: { id },
			header: {
				'content-type': 'application/json'
			}
		})
		console.log('小程序请求结果:', res)
		
		if (res.statusCode === 200 && res.data.code === 0) {
			courseDetail.value = res.data.data
			// 缓存课程信息
			uni.setStorageSync('currentCourse', res.data.data)
		} else {
			throw new Error(res.data?.message || '获取课程详情失败')
		}
		// #endif

		// #ifndef MP-WEIXIN
		res = await courseApi.getCourseDetail(id)
		console.log('课程详情:', res.data)
		if (res.code === 0) {
			courseDetail.value = res.data
		}
		// #endif
	} catch (error) {
		console.error('获取课程详情失败:', error)
		uni.showToast({
			title: error.message || '获取课程详情失败',
			icon: 'none'
		})
	}
}

onMounted(() => {
	// #ifdef MP-WEIXIN
	// 小程序端
	try {
		const query = uni.getLaunchOptionsSync().query
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		let courseId = null
		
		// 尝试多种方式获取课程ID
		if (currentPage && currentPage.options) {
			courseId = currentPage.options.id
		} else if (currentPage && currentPage.$page && currentPage.$page.options) {
			courseId = currentPage.$page.options.id
		} else if (query.id) {
			courseId = query.id
		}
		
		console.log('小程序端获取到的参数:', {
			currentPage,
			options: currentPage?.options,
			$page: currentPage?.$page,
			query,
			courseId
		})

		if (courseId) {
			getCourseDetail(courseId)
			// 获取章节索引
			let chapterIndex = null
			if (currentPage?.options?.chapter) {
				chapterIndex = parseInt(currentPage.options.chapter) - 1
			} else if (currentPage?.$page?.options?.chapter) {
				chapterIndex = parseInt(currentPage.$page.options.chapter) - 1
			} else if (query.chapter) {
				chapterIndex = parseInt(query.chapter) - 1
			}
			
			if (!isNaN(chapterIndex)) {
				currentChapterIndex.value = chapterIndex
			}
		} else {
			throw new Error('课程信息不存在')
		}
	} catch (error) {
		console.error('获取参数失败:', error)
		uni.showToast({
			title: error.message || '获取课程信息失败',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
	// #endif

	// #ifndef MP-WEIXIN
	// web端
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const courseId = currentPage.$page.options.id
	const chapterIndex = parseInt(currentPage.$page.options.chapter) - 1
	
	if (courseId) {
		getCourseDetail(courseId)
		if (!isNaN(chapterIndex)) {
			currentChapterIndex.value = chapterIndex
		}
	}
	// #endif
})
</script>

<style scoped>
.detail-container {
	padding-bottom: 120rpx;
}

.course-header {
	position: relative;
}

.course-banner {
	width: 100%;
	height: 400rpx;
}

.course-info {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 30rpx;
	background: linear-gradient(to top, rgba(0,0,0,0.8), transparent);
	color: #fff;
}

.course-title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.course-meta {
	font-size: 24rpx;
	opacity: 0.8;
}

.teacher {
	margin-right: 20rpx;
}

.tab-box {
	display: flex;
	background-color: #fff;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
}

.tab-item {
	flex: 1;
	text-align: center;
	font-size: 28rpx;
	color: #666;
	position: relative;
}

.tab-item.active {
	color: #007aff;
	font-weight: bold;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: -20rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 40rpx;
	height: 4rpx;
	background-color: #007aff;
	border-radius: 2rpx;
}

.content-swiper {
	height: calc(100vh - 580rpx);
}

.chapter-list,
.detail-content,
.comment-list {
	height: 100%;
	padding: 20rpx;
}

.chapter-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background-color: #fff;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
	transition: all 0.3s ease;
}

.chapter-item:active {
	background-color: #f5f5f5;
}

.chapter-title {
	display: flex;
	align-items: center;
}

.chapter-index {
	width: 40rpx;
	height: 40rpx;
	line-height: 40rpx;
	text-align: center;
	background-color: #007aff;
	color: #fff;
	border-radius: 20rpx;
	margin-right: 20rpx;
	font-size: 24rpx;
}

.chapter-duration {
	color: #999;
	font-size: 24rpx;
	margin-right: 10rpx;
}

.chapter-arrow {
	color: #999;
	font-size: 32rpx;
	font-family: serif;
}

.comment-item {
	display: flex;
	padding: 20rpx;
	background-color: #fff;
	margin-bottom: 20rpx;
	border-radius: 12rpx;
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	margin-right: 20rpx;
}

.comment-content {
	flex: 1;
}

.comment-header {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10rpx;
}

.user-name {
	font-size: 28rpx;
	color: #333;
}

.comment-time {
	font-size: 24rpx;
	color: #999;
}

.comment-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.6;
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.price-box {
	flex: 1;
}

.price {
	font-size: 40rpx;
	color: #ff6b6b;
	font-weight: bold;
}

.enroll-btn {
	width: 200rpx;
	height: 70rpx;
	line-height: 70rpx;
	background: linear-gradient(135deg, #007aff 0%, #0056b3 100%);
	color: #fff;
	border-radius: 35rpx;
	font-size: 28rpx;
	margin: 0;
}

.chapter-control {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.prev-btn,
.next-btn {
	width: 160rpx;
	height: 60rpx;
	line-height: 60rpx;
	font-size: 28rpx;
	color: #fff;
	background: linear-gradient(135deg, #007aff 0%, #0056b3 100%);
	border-radius: 30rpx;
	padding: 0;
	margin: 0;
}

.prev-btn[disabled],
.next-btn[disabled] {
	background: #ccc;
	opacity: 0.6;
}

.chapter-progress {
	font-size: 28rpx;
	color: #666;
}
</style> 